package com.tueye.service.job;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.Writer;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;

import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;

import com.tueye.base.util.Page;
import com.tueye.cache.TuEyeCache;
import com.tueye.entity.Pictures;
import com.tueye.entity.TopicType;
import com.tueye.entity.Topics;
import com.tueye.service.ITopicService;
import com.tueye.service.exception.TuEyeServiceException;
import com.tueye.utils.CreateHtmlUtil;
import com.tueye.utils.TuEyeConstant;

import freemarker.template.Configuration;
import freemarker.template.DefaultObjectWrapper;
import freemarker.template.Template;
import freemarker.template.TemplateException;

public class CreatePageList {
	
	Log log = LogFactory.getLog(CreatePageList.class);
	String file_spe = File.separator;
	@Autowired
	@Qualifier("topicService")
	ITopicService topicService;

	@Autowired
	@Qualifier("tueyecache")
	TuEyeCache tueyecache;
	
	 
	public void doIt() throws TuEyeServiceException, IOException, TemplateException{ 
		//拿到tueye cache 里面所有的type
		List<TopicType> topictypes = tueyecache.allTopicTypes();
		if(!topictypes.isEmpty()){
			for(Iterator iter =  topictypes.iterator(); iter.hasNext();){
				//查一次，知道有多少页，生成index.html
				TopicType topictype = (TopicType) iter.next(); 
				String hql = "from Topics t where  t.topic_type.id = '"+ topictype.getId() + "' and t.topic_release_type = 1 order by t.topic_clickCount desc,t.topic_uploadDate desc";
				Page page = topicService.pagedQueryByHQL(hql, 1, 12, null);
				String htmlFileName = TuEyeConstant.PROJECTPATH + topictype.getType_enlish_name() + file_spe + "index.html"; 
				String templatePath = TuEyeConstant.PROJECTPATH +file_spe+"WEB-INF"+ file_spe + "template";
				Configuration cfg = null;
				cfg = new Configuration();
				cfg.setDefaultEncoding("utf-8"); 
				cfg.setDirectoryForTemplateLoading(new File(templatePath));
				cfg.setObjectWrapper(new DefaultObjectWrapper()); 
				Template temp = cfg.getTemplate("topiclistshow.ftl");
				
				 
				HashMap contents = new HashMap();
				contents.put("title",StringUtils.isEmpty(topictype.getType_page_title())?"列表首页":topictype.getType_page_title());
				contents.put("keyword", StringUtils.isEmpty(topictype.getType_page_keywords())?"就爱看图网":topictype.getType_page_keywords());
				contents.put("description", StringUtils.isEmpty(topictype.getType_page_description())?"就爱看图网":topictype.getType_page_description());
				contents.put("contenttilte", StringUtils.isEmpty(topictype.getType_name())?"就爱看图网":topictype.getType_name());
				contents.put("imgcontent", getContent(page));
				contents.put("rmdj", getRmdj(topictype.getId()));
				contents.put("pagenum", CreateHtmlUtil.getPageNum(page.getCurrentPageNo(), page.getTotalPageCount(),topictype.getType_enlish_name()));
				contents.put("daohang", getDangHang(topictype));
				
				 Writer out = new OutputStreamWriter(new FileOutputStream(htmlFileName),"utf-8");
				 temp.process(contents, out);
				 out.flush();
				 out.close();
					
				//循环生成其他页
				for(int i = 2; i<= page.getTotalPageCount(); i++)
				{
					 
					Page page_temp = topicService.pagedQueryByHQL(hql, i, 12, null);
					String htmlFileName_temp = TuEyeConstant.PROJECTPATH + topictype.getType_enlish_name() + file_spe + topictype.getType_enlish_name()+"_"+i+".html"; 
					   
				 
			 
	 
					contents.put("imgcontent", getContent(page_temp));
					contents.put("pagenum", CreateHtmlUtil.getPageNum(page_temp.getCurrentPageNo(), page_temp.getTotalPageCount(),topictype.getType_enlish_name()));
					
					 Writer out_temp = new OutputStreamWriter(new FileOutputStream(htmlFileName_temp),"utf-8");
					 temp.process(contents, out_temp);
					 out_temp.flush();
					 out_temp.close();
				} 
			}
		}
		    
	}
	//设置主体内容
	private String getContent(Page page){
		
		 List<Topics> topics =  (List<Topics>) page.getResult();
		 if(topics.isEmpty())return "暂无记录";
		 StringBuffer sb = new StringBuffer();
		 for(Iterator iter = topics.iterator(); iter.hasNext();){
			 Topics topic = (Topics) iter.next();
			// <li><a href="#"><img src="../image/car.gif" height="120"  width="170"/></a>
			// <p><a href="#">好美的图片，我喜欢这个风格</a>
			// </p><p id="hitTotal">点击：12133<br />评论：8337</p></li>
			 String[] str  = getMainPictrueName(topic);
			 sb.append("<li><a href=\"")
			 	.append("./").append(topic.getTopic_code()).append("/index.html\" title='"+topic.getTopic_title()+"' target='_blank'>")
			 	.append("<img src=\"").append("./").append(topic.getTopic_code()).append("/")
			 	.append(str[0]).append("\"  onload=\"javascript:DrawImage(this,180,130)\"").append("alt=\"").append(str[1]+"\"")
			 	.append("/></a><p><a href=\"").append("./").append(topic.getTopic_code()).append("/index.html\" title='"+topic.getTopic_title()+"' target='_blank'>")
			 	.append(CreateHtmlUtil.subString(topic.getTopic_title(),13)).append("</a></p><p id=\"hitTotal\">点击:").append(tueyecache.getclickNumByTopicId(topic.getId()))
			 	.append("<br />评论:").append(topicService.getCommentsNumByTopicId(topic.getId())).append("</p></li>");
			 	
			 
		 }
		 //System.out.println("if the imgtilecontent's content is "+sb+" will have exception!!!!");
		  
		return sb.toString();
	}
	 
	 private String getDangHang(TopicType topictype){
		 StringBuffer sb = new StringBuffer();
		 sb.append("<a href='../index.html' title='首页'>首页</a>>><a href='#' title='").append(topictype.getType_name()).append("'>")
		   .append(topictype.getType_name()).append("</a>");
		 return sb.toString();
		   
	 }
	 
	
	private String[] getMainPictrueName(Topics topic){
		String [] str = new String[2];
		for(Iterator iter = topic.getPictures().iterator(); iter.hasNext();){
			Pictures pircture = (Pictures) iter.next();
			if(pircture.getMain_picture() == 1){
				str[0] = pircture.getPicture_url();
				String path =TuEyeConstant.PROJECTPATH+
				  File.separatorChar + topic.getTopic_type().getType_enlish_name()+
 				  File.separatorChar + topic.getTopic_code()+ File.separatorChar +"show"+pircture.getPicture_url();
				File f = new File(path);
				if(f.exists()){
					str[0] = "show"+pircture.getPicture_url();
				}
				str[1] = pircture.getPicture_name();
				  
			}
		}
		return str;
	}
	private String getRmdj(String id) throws TuEyeServiceException{
		String hql = "from Topics t where  t.topic_type.id = '"+ id + "' and t.topic_change=1 order by t.topic_clickCount desc,t.id ";
		Page page = topicService.pagedQueryByHQL(hql, 1, 10, null);
		List<Topics>  result = (List<Topics>) page.getResult();
		StringBuffer sb = new StringBuffer();
		for(Topics topic : result )
		{
			sb.append("<li><a href='./"+topic.getTopic_code()+"/index.html' title='"+topic.getTopic_title()+"'　target='_blank'> "+topic.getTopic_title()+"</a></li>");
		}
		
		
		return sb.toString();
	}
	 
}